package cn.hexcloud.dga.governance.assessor.quality;

import cn.hexcloud.dga.common.constant.MetaConst;
import cn.hexcloud.dga.ds.bean.TDsTaskInstance;
import cn.hexcloud.dga.ds.service.TDsTaskInstanceService;
import cn.hexcloud.dga.governance.assessor.Assessor;
import cn.hexcloud.dga.governance.bean.AssessParam;
import cn.hexcloud.dga.governance.bean.GovernanceAssessDetail;
import cn.hexcloud.dga.meta.bean.TableMetaInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

/**
 * @author q1603
 */
@Component("TIME_LINESS")
public class TimeLinessAssessor extends Assessor {
    @Autowired
    TDsTaskInstanceService tDsTaskInstanceService;

    @Override
    public void checkProblem(GovernanceAssessDetail governanceAssessDetail, AssessParam assessParam) throws Exception {
        if (assessParam.getTDsTaskDefinition() == null) {
            return;
        }
        // 获取参数
        String metricParamsJson = assessParam.getGovernanceMetric().getMetricParamsJson();
        JSONObject paramJsonObject = JSON.parseObject(metricParamsJson);
        Integer days = paramJsonObject.getInteger("days");
        BigDecimal percent = paramJsonObject.getBigDecimal("n");
        // 收集历史任务耗时
        Long historyCost = 0L;
        Integer dayCnt = 0;
        Long curCost = 0L;

        Date date = DateUtils.parseDate(assessParam.getAssessDate(), "yyyy-MM-dd");
        TableMetaInfo tableMetaInfo = assessParam.getTableMetaInfo();
        for (Integer i = days; i >= 0; i--) {
            String calcDate = DateFormatUtils.format(DateUtils.addDays(date, -i), "yyyy-MM-dd");
            Map<String, Object> resMap = tDsTaskInstanceService.getMap(new QueryWrapper<TDsTaskInstance>().eq("date_format(start_time,'%Y-%m-%d')", calcDate).eq("state", MetaConst.DS_TASK_SUCCESS).eq("name", tableMetaInfo.getSchemaName() + "." + tableMetaInfo.getTableName()).orderByDesc("start_time").select("(end_time - start_time) as during").last("limit 1"));
            Long during = 0L;
            if (resMap != null) {
                during = (long) resMap.get("during");
                if (i != 0) {
                    historyCost += (long) during;
                    dayCnt++;
                } else {
                    curCost = (long) during;
                }
            }
        }
        if(dayCnt == 0){
            return;
        }
        double avgHistoryCost = historyCost * 1d / dayCnt;
        BigDecimal rate = BigDecimal.valueOf((curCost - avgHistoryCost) * 1d / avgHistoryCost * 100).divide(BigDecimal.ONE,2, RoundingMode.HALF_UP);
        if (rate.compareTo(percent)>0) {
            governanceAssessDetail.setAssessScore(BigDecimal.ZERO);
            governanceAssessDetail.setAssessProblem("当日产出时效，超过前2天产出时效平均值" + rate + "%");
        }
    }

}
